import React, { useEffect, useState } from "react";
import { Card, Space, Table, Tag } from "antd";
import "./index.css";
import {
  SearchOutlined,
  PlusOutlined,
  FormOutlined,
  DeleteOutlined,
  LoadingOutlined,
} from "@ant-design/icons";
import { Button, Tooltip, Modal, Form, Input, message, Upload } from "antd";
import type { UploadChangeParam } from "antd/es/upload";
import type { RcFile, UploadFile, UploadProps } from "antd/es/upload/interface";
import type { ColumnsType } from "antd/es/table";
import {
  reqTradeMarkList,
  reqAddTradeMark,
  reqDelTradeMark,
} from "@/api/v2/trademark";
import { request } from "https";

export default function Index() {
  //分页器  当前页 和 每页多少个  总数
  const [page, setPage] = useState<any>(1);
  const [pageSize, setPageSize] = useState<any>(5);
  const [total, setTotal] = useState<any>();
  //用来存储数据的状态
  const [TradeMarkList, setTradeMarkList] = useState<any>([]);
  //定义点击添加弹出的状态
  const [open, setOpen] = useState<any>(false);
  //input 输入内容
  const [tradeMarkInput, setTradeMarkInput] = useState("");
  //上传图片的定义
  const [loading, setLoading] = useState(false);
  const [imageUrl, setImageUrl] = useState<string>();
  const [tradeMarkId, setTradeMarkId] = useState<any>();
  let [form] = Form.useForm();

  //组件挂载的时候发送请求
  useEffect(() => {
    getTradeMarkList(page, pageSize);
  }, []);
  async function getTradeMarkList(page: any, pageSize: any) {
    let rs = await reqTradeMarkList(page, pageSize);
    setTradeMarkList(rs.records);

    setTotal(rs.total);
  }
  //数组渲染
  const columns: ColumnsType<any> = [
    {
      title: "序号",
      render: (text, records, index) => index + 1,
      align: "center",
      width: 80,
    },
    {
      title: "品牌名称",
      dataIndex: "tmName",
    },
    {
      title: "品牌LOGO",
      render: (text, records, index) => {
        return <img src={records.logoUrl} className="imgLogo" />;
      },
    },
    {
      title: "操作",
      render: (text: any, records: any, index) => (
        <div key={index}>
          <Button
            onClick={() => {
              setOpen(true);

              form.setFieldsValue({ username: records.tmName });
              setImageUrl(records.logoUrl);
              setTradeMarkId(records.id);
            }}
            type="primary"
            icon={<FormOutlined />}
            style={{ marginRight: 10 }}
            className="bianji"
          ></Button>
          <Button
            onClick={() => {
              reqDelTradeMark(records.id);
              getTradeMarkList(page, pageSize);
            }}
            type="primary"
            icon={<DeleteOutlined />}
            className="deldeteBtn"
          ></Button>
        </div>
      ),
    },
  ];

  //控制Madel 点击确定的回调
  const hideModal = async () => {
    let { username } = form.getFieldsValue();
    setOpen(false);
    let data = {};
    if (tradeMarkId) {
      data = {
        tmName: username,
        logoUrl: imageUrl,
        id: tradeMarkId,
      };
    } else {
      data = {
        tmName: username,
        logoUrl: imageUrl,
      };
    }

    await reqAddTradeMark(data);

    form.setFieldsValue({
      username: "",
    });
    setImageUrl("");

    getTradeMarkList(page, pageSize);
  };
  const quxiao = () => {
    setOpen(false);
  };
  //添加按钮的回调
  const addHandle = async () => {

    setOpen(true);
    form.resetFields();
    setImageUrl("");
  };
  //上传图片

  const getBase64 = (img: RcFile, callback: (url: string) => void) => {
    const reader = new FileReader();
    reader.addEventListener("load", () => callback(reader.result as string));
    reader.readAsDataURL(img);
  };

  const beforeUpload = (file: RcFile) => {
    const isJpgOrPng = file.type === "image/jpeg" || file.type === "image/png";
    if (!isJpgOrPng) {
      message.error("You can only upload JPG/PNG file!");
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      message.error("Image must smaller than 2MB!");
    }
    return isJpgOrPng && isLt2M;
  };

  const handleChange: UploadProps["onChange"] = (
    info: UploadChangeParam<UploadFile>
  ) => {
    if (info.file.status === "uploading") {
      setLoading(true);
      return;
    }
    if (info.file.status === "done") {
      // Get this url from response in real world.

      getBase64(info.file.originFileObj as RcFile, (url) => {
        setLoading(false);
        setImageUrl(info.file.response.data);
      });
    }
  };

  const uploadButton = (
    <div>
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </div>
  );

  return (
    <div className="rongqi">
      <Card>
        <Button type="primary" icon={<PlusOutlined />} onClick={addHandle}>
          {" "}
          添加
        </Button>
        <Modal
          visible={open}
          title={tradeMarkId ? "修改品牌" : "添加品牌"}
          onOk={hideModal}
          onCancel={quxiao}
          okText="确认"
          cancelText="取消"
        >
          <Form
            form={form}
            name="basic"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ remember: true }}
            autoComplete="off"
          >
            <Form.Item
              label="品牌名称"
              name="username"
              rules={[
                { required: true, message: "Please input your username!" },
              ]}
            >
              <Input value={tradeMarkInput} />
            </Form.Item>
            <Form.Item label="品牌Logo">
              <Upload
                name="file"
                listType="picture-card"
                className="avatar-uploader"
                showUploadList={false}
                action="/dev-api/admin/product/upload"
                beforeUpload={beforeUpload}
                onChange={handleChange}
              >
                {imageUrl ? (
                  <img src={imageUrl} alt="file" style={{ width: "100%" }} />
                ) : (
                  uploadButton
                )}
              </Upload>
            </Form.Item>
          </Form>
        </Modal>
        {/* dataSource是要渲染数据   columns表格列的配置描述 */}
        <Table
          rowKey="id"
          columns={columns}
          dataSource={TradeMarkList}
          bordered
          pagination={{
            total,
            current: page,
            pageSize,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: [5, 10, 15],
            showTotal: (total) => {
              return `总共:${total}条`;
            },
            onChange: (page, pageSize) => {
              setPage(page);
              setPageSize(pageSize);
              getTradeMarkList(page, pageSize);
            },
          }}
        />
      </Card>
    </div>
  );
}
